#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
int split(char *line, char *argv[])
{
    int buff_size = strlen(line) + 1;
    char buff[buff_size];
    strcpy(buff, line);

    int argc = 0;
    char *arg;

    arg = strtok(buff, " ");
    while (arg != NULL)
    {
        argv[argc] = arg;
        printf("%s\n", argv[argc]);
        argc++;
        arg = strtok(NULL, " ");
    }
    argv[argc] = NULL;
    return argc;
}

// 测试程序，打印切割后的字符串
void dump_args(int argc, char *argv[])
{
    for (int i = 0; i < argc; i++)
    {
        printf("[%s]\n", argv[i]);
    }
}

#define MAX_ARGC 100
int mysys(char *command)
{
    if (command == NULL)
    {
        return 1;
    }

    int buff_size = strlen(command) + 1;
    char buff[buff_size];
    strcpy(buff, command);

    char *argv[MAX_ARGC];
    int argc = split(buff, argv);
    pid_t pid = fork();

    if (pid == 0)
    {
        int error = execvp(argv[0], argv);
        if (error < 0)
        {
            perror("execvp");
            exit(EXIT_FAILURE);
        }
    }
    wait(NULL);
}

int main()
{
    printf("--------------------------------------------------\n");
    mysys("echo HELLO WORLD");
    printf("--------------------------------------------------\n");
    mysys("ls /");
    printf("--------------------------------------------------\n");
    return 0;
}